package com.asteros.crypto.utils.certs;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.cert.CertStore;
import java.security.cert.CertificateFactory;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class CertStoresEnv {
	private CertificateFactory cf ;
	private List<CertStore> certStores = new ArrayList<CertStore>();

	public CertStoresEnv(CertificateFactory certificateFactory) throws Exception{
		if (certificateFactory == null) {
			throw new Exception("CertStoresEnv creation failed");
		}
		this.cf = certificateFactory;
	}

	public List<CertStore> getCertStores() {
		return certStores;
	}

	public void addCert(X509Certificate cert) throws Exception {
		List<X509Certificate> certs = new ArrayList<X509Certificate>();
		certs.add(cert);
		addCerts(certs);
	}
	
	public void addCerts(Collection<X509Certificate> certs) throws Exception {
		addCerts(new CollectionCertStoreParameters(certs));
	}

	public void addCerts(CollectionCertStoreParameters params) throws Exception {
		certStores.add(CertStore.getInstance("Collection", params ));
	}
	
	public void loadCertFile(String filename) throws Exception {
		loadCertFile(new File(filename));
	}
	
	public void loadCertFile(File file) throws Exception {
		System.out.println("Cert File loading...");
		
		FileInputStream in = new FileInputStream(file); 
		X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
		in.close();		
		
		addCert(cert);
	}
	
	public void loadCRL(byte[] data) throws Exception {
		System.out.println("CRL File loading...");
		
		ByteArrayInputStream in = new ByteArrayInputStream(data);
		loadCRL(in);
		in.close();
	}
	
	public void loadCRL(String filename) throws Exception {
		loadCRL(new File(filename));
	}

	public void loadCRL(File file) throws Exception {
		System.out.println("CRL File loading...");
		
		FileInputStream in = new FileInputStream(file); 
		loadCRL(in);
		in.close();
	}

	public void loadCRL(InputStream in) throws Exception {
		CollectionCertStoreParameters par = 
			new CollectionCertStoreParameters(cf.generateCRLs(in));
		
		addCerts(par);
	}
}
